/*
 * @Description: 请描述此文件
 * @Author: LDM
 * @Date: 2021-09-13 17:44:40
 * @LastEditors: LDM
 * @LastEditTime: 2021-09-30 16:32:38
 */
import type { IAppRouteRecordRaw } from '/@/router/types'
import type { Ref } from 'vue'
import { defineStore, acceptHMRUpdate } from 'pinia'
import { pinia } from '/@/store'
import { otherRoutes } from '/@/router'
import { basicRoutes } from '/@/router/basicRoutes'
import { markRaw, shallowRef } from 'vue'
interface IPermisionnState {
  routes: IAppRouteRecordRaw[]
  roleCheck: boolean
}
export const usePermisionnStore = defineStore('permission', {
  state: (): IPermisionnState => ({
    routes: [],
    roleCheck: false
  }),
  actions: {
    SetPermissionRoutes(newRoutes: IAppRouteRecordRaw[]) {
      this.routes = markRaw([...basicRoutes, ...newRoutes])
      console.log(
        '%c 🍲 this.routes: ',
        'font-size:20px;background-color: #3F7CFF;color:#fff;',
        this.routes
      )
    },
    UpdatePermissionRoutes(roles: number[]) {
      if (!roles) return
      this.SetPermissionRoutes(this.roleCheck ? this.filterRoutes(roles, otherRoutes) : otherRoutes)
    },
    filterRoutes(roles: number[], childrenRoutes: IAppRouteRecordRaw[]): IAppRouteRecordRaw[] {
      console.log(123123)

      const result = [] as IAppRouteRecordRaw[]
      childrenRoutes.forEach((route) => {
        const { role: t } = route.meta || {}
        const newRoute: IAppRouteRecordRaw = { ...route, children: [] }
        if (!t || roles.includes(t)) {
          if (route.children && route.children.length) {
            newRoute.children = this.filterRoutes(roles, route.children)
          }
          result.push(route)
        }
      })
      return result
    }
  },
  getters: {
    getRoutes(): Ref<IAppRouteRecordRaw[]> {
      return shallowRef(this.routes)
    }
  }
})

/**
 * @description: 在setup外使用仓库时调用
 * @return {*} 返回AppStore
 */
export function usePermisionnStoreWithOut() {
  return usePermisionnStore(pinia)
}

// make sure to pass the right store definition, `useAuth` in this case.
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(usePermisionnStore, import.meta.hot))
}
